package com.xyz.jira.plugin;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.atlassian.core.user.UserUtils;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.config.properties.ApplicationProperties;
import com.atlassian.jira.exception.CreateException;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.project.version.VersionManager;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueCreated;
import com.xyz.jira.plugin.responses.Message;
import com.opensymphony.user.EntityNotFoundException;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.ofbiz.core.entity.GenericValue;

/**
 * A resource of message.
 */
@Path("/createAnonIssue")
public class CreateAnonIssue {

	/**
	 * This method will be called if no extra path information is used in the
	 * request.
	 * 
	 * @param key
	 *            optional key for the message
	 * @return the message from the key parameter or the default message
	 */
	@POST
	@AnonymousAllowed
	@Produces({ MediaType.APPLICATION_JSON })
	public Response createIssue(@FormParam("pid") String pid,
			@FormParam("summary") String summary,
			@FormParam("issuetype") String issueType,
			@FormParam("priority") String priority,
			@FormParam("description") String description,
			@FormParam("reporter") String reporter,
			@FormParam("duedate") String dueDate,
			@FormParam("customfields") String customFields) {

		IssueFactory issueFactory = ComponentManager.getInstance()
				.getIssueFactory();
		ProjectManager projectManager = ComponentManager.getInstance()
				.getProjectManager();
		ConstantsManager constantsManager = ComponentManager.getInstance()
				.getConstantsManager();
		VersionManager versionManager = ComponentManager.getInstance()
				.getVersionManager();
		CustomFieldManager customFieldManager = ComponentManager.getInstance()
				.getCustomFieldManager();
		IssueManager issueManager = ComponentManager.getInstance()
				.getIssueManager();
		JiraAuthenticationContext authenticationContext = ComponentManager
				.getInstance().getJiraAuthenticationContext();
		// Regular Fields
		Project project = ComponentManager.getInstance().getProjectManager()
				.getProjectObj(new Long(pid));
		MutableIssue issueObject = issueFactory.getIssue();
		issueObject.setProject(project.getGenericValue());
		issueObject.setIssueType(constantsManager.getIssueType(issueType));
		issueObject.setSummary(summary);
		if (reporter != null && reporter.length() > 0) {
			try {
				issueObject.setReporter(UserUtils.getUser(reporter));
			} catch (EntityNotFoundException enf) {
				// We are creating anonymously, this is ok
			}
		}
		// issueObject.setAssignee(null);
		issueObject.setPriority(constantsManager.getPriority(priority));
		issueObject.setDescription(description);
		if ( dueDate != null && dueDate.trim().length() > 0 ) {
			ApplicationProperties ap = ComponentManager.getInstance().getApplicationProperties();
			String dateFormat = ap.getString("jira.date.picker.java.format");
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			try {
				Date date = sdf.parse(dueDate);
				Timestamp tStamp = new Timestamp(date.getTime());
				issueObject.setDueDate(tStamp);
			} catch ( ParseException pe ) {
				// Ignore. The format should had been tested by javascript
			}
		}
		// issueObject.setAffectedVersions(EasyList.build(versionManager.getVersion(new
		// Long(10000)), versionManager.getVersion(new Long(10001))));
		// issueObject.setFixVersions(EasyList.build(versionManager.getVersion(new
		// Long(10002))));
		// issueObject.setComponents(EasyList.build(projectManager.getComponent(new
		// Long(10000)), projectManager.getComponent(new Long(10001))));

		// Custom fields
		if (customFields != null && customFields.length() > 0) {
			String[] pairs = customFields.split(";");
			String tmp[];
			for (String pair : pairs) {
				tmp = pair.split("=");
				String id = tmp[0];
				String value = "";
				if (tmp.length > 1) {
					value = tmp[1];
				}
				CustomField customField = customFieldManager
						.getCustomFieldObject(new Long(id));
				issueObject.setCustomFieldValue(customField, value);
			}
		}

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("issue", issueObject);
			GenericValue issue = issueManager.createIssue(
					authenticationContext.getUser(), params);
		} catch (CreateException ce) {
			return Response
					.ok(new Message(pid,
							"Issue Creation Failed. Please Contact JIRA administrators."))
					.build();
		}

		return Response.ok(
				new IssueCreated(pid, issueObject.getId() + "", issueObject
						.getKey())).build();
	}
}